<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redis;
class ResetPasswordController extends Controller
{

    public function __construct()
    {
        $this->middleware('guest');
    }

    public function resetCodeSms(Request $request)
    {
        $s=Validator::make($request->all(), [
            'mobile' =>[
                "required",
                "regex:/^(\+?0?86\-?)?((13\d|14[57]|15[^4,\D]|17[3678]|18\d)\d{8}|170[059]\d{7})$/",
            ],
            'CodeSms' =>'required'
        ],[
            'mobile'=>'请输入正确手机号码',
            'CodeSms.required'=> '手机验证码不能为空',
        ])->validate();
        $results = DB::select('select * from password_resets where mobile = :mobile and token=:token', [
            'mobile' =>$request->input('mobile'),'token'=>$request->input('CodeSms')
        ]);
        if($results){
            $minute=floor((time()-strtotime($results[0]->created_at))%86400/60);
            $second=floor((time()-strtotime($results[0]->created_at))%86400%60);
            if(($minute*60+$second)>60*20 ){
                //如果验证码超过20分钟没做验证则失效
                 DB::delete('delete from password_resets where mobile = :mobile and token=:token', [
                    'mobile' =>$request->input('mobile'),
                    'token'=>$request->input('CodeSms')
                ]);
                return redirect()->route('password.request')->with('danger', '验证码已经失效，请重新操作');
            }

            if($request->input('mobile')== $results[0]->mobile && $request->input('CodeSms')== $results[0]->token){
                $randStr = str_shuffle('1234567890abcdefghijklmnopqrstuywxyz');
                $code = substr($randStr,0,6);
                $user = User::where('mobile', $results[0]->mobile)->first();
                $user->password=bcrypt($code);
                $user->save();
                seed_sms_code($results[0]->mobile,"【爱达人】您刚刚重置了密码，新密码为".$code." 请尽快修改密码。",  $code);

                return redirect()->route('login')->with('success', '新密码已经发送到您到手机，请注意查收。');
            }else{

                return redirect()->route('password.request')->with('danger', '输入信息错误，请重新进行验证');
            }
        }else{
            return back()->with('danger', '手机号或验证码不正确，请重新进行输入');
//
//            $cishu = Redis::get('cishu');
//            Redis::set('cishu',$cishu+1);
//
//            if( Redis::get('cishu')>3){
//                $cishu=0;
//                Redis::set('cishu',$cishu);
//                return redirect()->route('password.request')->with('danger', '输入错误次数过多，请重新发送验证码。');
//            }else{
//                return back()->with('danger', '手机号或验证码不正确，请重新进行输入');
//            }

        }

    }
}
